<?php namespace Admin\Model;

use Hdphp\Model\Model;

class Pics extends Model{

	//数据表
	protected $table = "shop_pics";

	//完整表名
	protected $full = false;

	//自动验证
	protected $validate=array(
	);

	//自动完成
	protected $auto=array(
	);

	//保存图片到数据库方法
	public function store($goods_id)
	{
		//通过框架方法，上传文件
		$pics = Upload::path('Upload/Goods')->make('pics');
		//遍历上传出来的数据
		foreach ((array)$pics as $pic) 
		{
			// 生成中图，设置中图的路径地址变量
			$middlePic = $pic['dir'].'/'.$pic['fieldname'].'/'.$pic['filename'].'_middle.'.$pic['ext'];
			//用框架下的方法，生成缩略图
			Image::thumb($pic['path'], $middlePic, 400, 400, 5);
			//设置小图路径地址变量
			$smallPic = $pic['dir'].'/'.$pic['fieldname'].'/'.$pic['filename'].'_small.'.$pic['ext'];
			// 生成缩略图
			Image::thumb($pic['path'], $smallPic, 100, 100, 5);

			// 已经保存图了，再将地址数据压入数据库
			$data['big_pic'] = $pic['path'];
			$data['middle_pic'] = $middlePic;
			$data['small_pic'] = $smallPic;
			$data['hd_shop_goods_goods_id'] = $goods_id;
			//这样写更高效， 如果使用Db模型的话，每次都会生成一个实例
			$this->insert($data);			
		}
		return true;
	}

	// 抽取对应goods_id的图片资源
	public function only($hd_shop_goods_goods_id)
	{
		return $this->where('hd_shop_goods_goods_id',$hd_shop_goods_goods_id)->get();
	}

	//删除图片方法
	public function remove($id)
	{
		//抽取数据
		$pics = $this->find($id);
		// 判断是否合法文件类型，然后删除
		is_file($pics['big_pic']) and unlink($pics['big_pic']);
		is_file($pics['middle_pic']) and unlink($pics['middle_pic']);
		is_file($pics['small_pic']) and unlink($pics['small_pic']);
		//删除数据
		return $this->where('id',$id)->delete();

	}
}